from django.db import models
from django.core.validators import MinLengthValidator
import uuid
from datetime import datetime
from django.utils import timezone


class City(models.Model):
    name = models.CharField(max_length=100, unique=True)
    code = models.CharField(max_length=10, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.name} ({self.code})"


class DataCenter(models.Model):
    name = models.CharField(max_length=100)
    city = models.ForeignKey(City, on_delete=models.CASCADE, related_name='data_centers')
    address = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('name', 'city')

    def __str__(self):
        return f"{self.name} - {self.city.name}"


class Host(models.Model):
    STATUS_CHOICES = [
        ('active', 'Active'),
        ('maintenance', 'Maintenance'),
        ('decommissioned', 'Decommissioned'),
    ]

    hostname = models.CharField(max_length=100, unique=True)
    ip_address = models.GenericIPAddressField(unique=True)
    data_center = models.ForeignKey(DataCenter, on_delete=models.CASCADE, related_name='hosts')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.hostname} ({self.ip_address})"


class HostCredential(models.Model):
    host = models.OneToOneField(Host, on_delete=models.CASCADE, related_name='credential')
    root_password = models.CharField(max_length=100)
    last_updated = models.DateTimeField(auto_now=True)
    history = models.JSONField(default=list)

    def save(self, *args, **kwargs):
        if self.pk:
            original = HostCredential.objects.get(pk=self.pk)
            if original.root_password != self.root_password:
                history_entry = {
                    'password': original.root_password,
                    'changed_at': timezone.now().isoformat()
                }
                if not self.history:
                    self.history = []
                self.history.append(history_entry)
                self.history = self.history[-10:]
        super().save(*args, **kwargs)

    def __str__(self):
        return f"Credentials for {self.host.hostname}"


class HostStatistic(models.Model):
    city = models.ForeignKey(City, on_delete=models.CASCADE)
    data_center = models.ForeignKey(DataCenter, on_delete=models.CASCADE)
    host_count = models.PositiveIntegerField()
    date = models.DateField()
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('city', 'data_center', 'date')

    def __str__(self):
        return f"{self.date}: {self.data_center.name} - {self.host_count} hosts"